package fruitshopmall.Controller;

import fruitshopmall.Entity.*;
import fruitshopmall.Service.*;
import fruitshopmall.utils.Pager;
import fruitshopmall.utils.SystemContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static org.springframework.util.ObjectUtils.isEmpty;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: LittleFisher
 * @Date: 2021/12/26/10:06
 * @Description:
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private ManageService manageService;
    @Autowired
    private ItemCategoryService itemCategoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ItemOrderService itemOrderService;
    /**
     *  测试 接口是否能跑起来
     * @return
     */
    @RequestMapping("test")
    @ResponseBody
    public String test(){
        return "admin api test";
    }

    /**
     * 完成
     * @param username
     * @param password
     * @return 成功就返回token code 20000 ,失败code 60204 message "Account and password are incorrect."
     */
    @RequestMapping("login")
    @ResponseBody
    public Result login(String username,String password ) {
        Manage manage = new Manage(username,password);
        if (manage.getUserName() == null&&manage.getPassWord()==null) {
            Result rs1 = new Result<Token>(60204, "Account and password are incorrect.");

            return rs1;

        }
        //do your crud
        Manage byEntity = manageService.getByEntity(manage);
        //账号密码正确
        Token token = new Token("admin-token");
        Result rs = new Result<Token>(20000, token);
        //账号密码不正确
        //Result rs = new Result<Token>(60204,"Account and password are incorrect.");
        if (byEntity == null) {
            Result rs1 = new Result<Token>(60204, "Account and password are incorrect.");

            return rs1;

        }
        return rs;

    }

    /**
     * 管理员退出登录 已完成
     * @return
     */
    @RequestMapping("logout")
    @ResponseBody
    public Result loginOut(){
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }

    /**
     * 完成
     * 管理员获取所有用户信息
     * @return data ArrayList<user>
     */
    @RequestMapping("getAllUser")
    @ResponseBody
    public Result getAllUser(User user){
        String sql = "select * from user where 1=1 ";
        if(!isEmpty(user.getUserName())){
            sql += " and userName like '%"+user.getUserName()+"%' ";
        }
        sql+=" order by id";
        Pager<User> pagers = userService.findBySqlRerturnEntity(sql);
        //do you crud
        Result rs = new Result<List>(20000,pagers.getDatas());
        return rs;
    }
    /**
     * 完成
     * 管理员根据名字搜索用户信息
     * @return data ArrayList<user>
     */
    @RequestMapping("getUser")
    @ResponseBody
    public Result getUser(User user){
        String sql = "select * from user where 1=1 ";
        if(!isEmpty(user.getUserName())){
            sql += " and userName like '%"+user.getUserName()+"%' ";
        }
        sql+=" order by id";
        Pager<User> pagers = userService.findBySqlRerturnEntity(sql);
        //do you crud
        Result rs = new Result<List>(20000,pagers.getDatas());
        return rs;
    }
    /**
     * 完成
     * 管理员删除用户信息
     * @return data ArrayList<user>
     */
    @RequestMapping("delUserById")
    @ResponseBody
    public Result delUserById(Integer id){
        //删除本身
        userService.deleteById(id);

        if (id==null){
            Result rs = new Result<Object>(60204, "删除失败");
            return rs;
        }
        Result rs = new Result<Object>(20000, "success");
        return rs;
    }
    /**
     * 完成
     * 管理员获取所有公告
     * @return data ArrayList<news>
     */
    @RequestMapping("getAllNews")
    @ResponseBody
    public Result getAllNews(News news){
        String sql = "select * from news where 1=1 ";
        if(!isEmpty(news.getName())){
            sql += " and name like '%"+news.getName()+"%'";
        }
        sql += " order by id desc";
        Pager<News> pagers = newsService.findBySqlRerturnEntity(sql);
        //do you crud
        Result rs = new Result<Pager<News>>(20000,pagers);
        return rs;
    }
    /**
     * 管理员添加执行News
     * @return
     */
    @RequestMapping("/addNew")
    @ResponseBody
    public Result addNews(News news){
        news.setAddTime(new Date());
        newsService.insert(news);
        if (news.getName()==null&&news.getContent()==null){
            Result rs = new Result<Object>(60204, "添加失败");
            return rs;
        }

        Result rs = new Result<Object>(20000,news);
        return rs;
    }
    /**
     * 管理员修改公告
     * @return
     */
    @RequestMapping("editNew")
    @ResponseBody
    public Result exUpdateNews(News news){
        newsService.updateById(news);
        if (news==null){
            Result rs = new Result<Object>(60204, "修改失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,"success");
        return rs;

    }

    /**
     * 管理员修改公告删除公告
     * @return
     */
    @RequestMapping("delNewById")
    @ResponseBody
    public Result delNewById(Integer id){
        newsService.deleteById(id);
        if (id==null){
            Result rs = new Result<Object>(60204, "删除失败");
            return rs;
        }
        Result rs = new Result<Object>(20000, "success");
        return rs;
    }
    /**
     * 未完成
     * 管理员获取销售情况 先查询所有类目的id 再去订单表统计
     * @return data ArrayList<news>
     */
   /* @RequestMapping("getSaleResult")
    @ResponseBody
    public Result getSaleResult(){

        //do you crud
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }*/

    /**
     * 分页查询一级类目列表
     * @return
     */
    @RequestMapping("/getAllCategory")
    @ResponseBody
    public Result<List> findBySql(ItemCategory itemCategory){
        String sql = "select * from item_category where isDelete = 0 and pid is null order by id";
        Pager<ItemCategory> pagers = itemCategoryService.findBySqlRerturnEntity(sql);
        Result rs = new Result<List>(20000, pagers.getDatas());
        return rs;
    }

    /**
     * 新增一级类目保存功能
     * gei name
     * @return
     */
    @RequestMapping("/addOneCategory")
    @ResponseBody
    public Result exAdd(ItemCategory itemCategory){
        itemCategory.setIsDelete(0);
        itemCategoryService.insert(itemCategory);
        ArrayList<Object> list=new ArrayList<Object>();
        if (itemCategory.getName()==null){
            Result rs = new Result<Object>(60204, "添加失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,itemCategory);
        return rs;
    }
    /**
     * 修改一级类目
     * gei id,name
     * @return
     */
    @RequestMapping("/editOneCategory")
    @ResponseBody
    public Result exUpdate(ItemCategory itemCategory){
        itemCategoryService.updateById(itemCategory);
        if (itemCategory==null){
            Result rs = new Result<Object>(60204, "修改失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }
    /**
     * 删除一级类目
     * gei id
     * @return
     */
    @RequestMapping("/delCategoryById")
    @ResponseBody
    public Result delete(Integer id){
        //删除本身
        ItemCategory load = itemCategoryService.load(id);
        load.setIsDelete(1);
        itemCategoryService.updateById(load);
        //将下级也删除
        String sql = "update item_category set isDelete=1 where pid="+id;
        itemCategoryService.updateBysql(sql);
        if (id==null){
            Result rs = new Result<Object>(60204, "删除失败");
            return rs;
        }
        Result rs = new Result<Object>(20000, "success");
        return rs;
    }
    /**
     * 查看二级类目
     * @return
     * gei pid,也是一级的ID
     */
    @RequestMapping("/getTwoCategoryById")
    @ResponseBody
    public Result findBySql2(ItemCategory itemCategory, Model model){
        String sql = "select * from item_category where isDelete=0 and pid="+itemCategory.getId()+" order by id";
        Pager<ItemCategory> pagers = itemCategoryService.findBySqlRerturnEntity(sql);
        Result rs = new Result<List>(20000, pagers.getDatas());
        return rs;
    }
    /**
     * 新增二级类目保存功能
     *给 pid,name
     */
    @RequestMapping("/addTwoCategory")
    @ResponseBody
    public Result exAdd2(ItemCategory itemCategory){
        itemCategory.setIsDelete(0);
        itemCategoryService.insert(itemCategory);
        if (itemCategory.getName()==null&&itemCategory.getPid()==null){
            Result rs = new Result<Token>(60204, "添加失败");
            return rs;
        }
        Result rs = new Result<>(20000, itemCategory);
        return rs;
    }
    /**
     * 修改二级类目
     * gei id,name
     * @return
     */
    @RequestMapping("/editTwoCategory")
    @ResponseBody
    public Result exUpdate2(ItemCategory itemCategory){
        itemCategoryService.updateById(itemCategory);
        if (itemCategory==null){
            Result rs = new Result<Object>(60204, "修改失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }
    /**
     * 删除二级类目
     * gei id
     * @return
     */
    @RequestMapping("/delTwoCategoryById")
    @ResponseBody
    public Result delete2(Integer id,Integer pid){
        //删除本身
        ItemCategory load = itemCategoryService.load(id);
        load.setIsDelete(1);
        itemCategoryService.updateById(load);
        if (id==null){
            Result rs = new Result<Object>(60204, "删除失败");
            return rs;
        }
        Result rs = new Result<Object>(20000, "success");
        return rs;
    }


    /**
     * 分页查询商品列表
     * @return
     */
    @RequestMapping("/getItemById")
    @ResponseBody
    public Result findBySql(Item item){
        String sql = "select * from item where isDelete = 0 ";
        if(!isEmpty(item.getName())){
            sql += " and name like '%" + item.getName() + "%' ";
        }
        sql += " order by id desc";
        Pager<Item> pagers = itemService.findBySqlRerturnEntity(sql);

        Result rs = new Result<List>(20000, pagers.getDatas());
        return rs;
    }
    /**
     * 执行添加商品
     * @return
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public Result exAdd(Item item, @RequestParam("file") MultipartFile file) throws IOException {


        if (!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println(path);
            File upload = new File(path.getAbsolutePath(),"static/images/upload/");
            System.out.println(SystemContext.getRealPath());

            File dest = new File(("D:\\编程\\apache-tomcat-8.5.66\\webapps\\test1_war_exploded\\resource\\ueditor\\upload\\"  +  fileName));

           // File dest = new File(("G:\\apache-tomcat-8.5.60\\webapps\\test1_war_exploded\\resource\\ueditor\\upload\\"  +  fileName));

            file.transferTo(dest);
            System.out.println(dest);
            String a="\\test1_war_exploded\\resource\\ueditor\\upload\\"+fileName;
            item.setUrl1(a);

        }

        item.setGmNum(0);
        item.setIsDelete(0);
        item.setScNum(0);
         itemService.insert(item);
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }

    /**
     * 执行修改商品
     * @return
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public Result exUpdate(Item item, @RequestParam("file")MultipartFile file) throws IOException {
        if (!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println(path);
            File upload = new File(path.getAbsolutePath(),"static/images/upload/");
            System.out.println(SystemContext.getRealPath());
            File dest = new File(("D:\\编程\\apache-tomcat-8.5.66\\webapps\\test1_war_exploded\\resource\\ueditor\\upload\\"  +  fileName));
            file.transferTo(dest);
            String a="\\test1_war_exploded\\resource\\ueditor\\upload\\"+fileName;
            item.setUrl1(a);
        }
        itemService.updateById(item);
        if (item==null){
            Result rs = new Result<Object>(60204, "修改失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }
    /**
     * 商品下架
     * @return
     */
    @RequestMapping("/delCommodityById")
    @ResponseBody
    public Result update(Integer id){
        if (id==null){
        Result rs = new Result<Object>(60204, "删除失败");
        return rs;
    }
        Item obj = itemService.load(id);
        obj.setIsDelete(1);
        itemService.updateById(obj);

        Result rs = new Result<Object>(20000, "success");
        return rs;

    }

    @RequestMapping("/getSaleResult")
    @ResponseBody
    public Result tj(ItemCategory itemCategory){
        String sql = "select * from item_category where isDelete = 0 and pid is null order by id desc";
        List<ItemCategory> list=itemCategoryService.listBySqlReturnEntity(sql);
        List<Map<String,Object>> maps=new ArrayList<Map<String,Object>>();
        List<Tjdot> res=new ArrayList<Tjdot>();
        if (!CollectionUtils.isEmpty(list)){
            for (ItemCategory c : list){
                Tjdot td=new Tjdot();
                int tot=0;
                List<Item> listBySqlReturnEntity=itemService.listBySqlReturnEntity("select * from item where 1=1 and isDelete = 0 and category_id_one="+c.getId());
                if (!CollectionUtils.isEmpty(listBySqlReturnEntity)){
                   for (Item i : listBySqlReturnEntity){
                       tot+=i.getGmNum();
                   }
                }
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("name",c.getName());
                map.put("value",tot);
                maps.add(map);
            }
        }
        Result<Object> rs= new Result<>(20000,maps);
        return rs;
    }
    /**
     * 订单详情c层
     * gei orderId
     */
    @RequestMapping("/searchGoodDetailById")
    @ResponseBody
    public Result ulist(OrderDetail orderDetail){
        //分页查询
        String sql = "select * from order_detail  where order_id="+orderDetail.getOrderId();
        Pager<OrderDetail> pagers = orderDetailService.findBySqlRerturnEntity(sql);
        Result rs = new Result<List>(20000,pagers.getDatas());
        return rs;
    }
    /**
     * 订单管理列表
     * 通过 code查和不传值查全部订单
     * @return
     */
    @RequestMapping("/searchOrderByCode")
    @ResponseBody
    public Result findBySql(ItemOrder itemOrder){
        //分页查询
        String sql = "select * from item_order where 1=1 ";
        if(!(isEmpty(itemOrder.getCode()))){
            sql +=" and code like '%"+itemOrder.getCode()+"%' ";
        }
        sql += " order by id desc";
        Pager<ItemOrder> pagers = itemOrderService.findBySqlRerturnEntity(sql);
        Result rs = new Result<List>(20000,pagers.getDatas());
        return rs;
    }
    /**
     * 后台发货
     * @return
     */
    @RequestMapping("/toSendGood")
    @ResponseBody
    public Result fh(Integer id){
        ItemOrder obj =itemOrderService.load(id);
        obj.setStatus(2);
        itemOrderService.updateById(obj);
        if (id==null){
            Result rs = new Result<Object>(60204, "发货失败");
            return rs;
        }
        Result rs = new Result<Object>(20000,"success");
        return rs;
    }
}
